package com.xingfudazi.app.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.xingfudazi.acl.cache.CacheClient;
import com.xingfudazi.app.domain.AppEntrust;
import com.xingfudazi.app.dto.MemberAvatar;
import com.xingfudazi.app.mapper.AppEntrustMapper;
import com.xingfudazi.app.service.IAppEntrustService;
import com.xingfudazi.app.service.IAppMemberInfoService;
import com.xingfudazi.common.enums.DBDataStatus;
import com.xingfudazi.common.exception.ServiceException;
import com.xingfudazi.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * 委托关系Service业务层处理
 *
 * @author ruoyi
 * @date 2024-06-21
 */
@Service
public class AppEntrustServiceImpl implements IAppEntrustService {
    @Autowired
    private AppEntrustMapper appEntrustMapper;

    @Autowired
    private IAppMemberInfoService appMemberInfoService;

    /**
     * 查询委托关系
     *
     * @param id 委托关系主键
     * @return 委托关系
     */
    @Override
    public AppEntrust selectAppEntrustById(Long id) {
        return appEntrustMapper.selectById(id);
    }

    /**
     * 查询委托关系列表
     *
     * @param appEntrust 委托关系
     * @return 委托关系
     */
    @Override
    public List<AppEntrust> selectAppEntrustList(AppEntrust appEntrust) {
        LambdaQueryWrapper<AppEntrust> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(AppEntrust::getCreateTime);
        return appEntrustMapper.selectList(wrapper);
    }

    /**
     * 新增委托关系
     *
     * @param code 委托关系
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertAppEntrust(String code) {
        Object cacheObject = cacheClient.getCacheObject(KEY + code);
        if (cacheObject == null) {
            throw new ServiceException("验证码码超过24h，已失效");
        }

        Long clientId = Long.valueOf(cacheObject.toString());

        LambdaQueryWrapper<AppEntrust> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AppEntrust::getNid, SecurityUtils.getUserId());
        wrapper.eq(AppEntrust::getClientId, clientId);
        wrapper.eq(AppEntrust::getDelFlag, DBDataStatus.OK.getCode());

        if (this.appEntrustMapper.selectCount(wrapper) > 0) {
            throw new ServiceException("请勿重复添加");
        }

        AppEntrust appEntrust = new AppEntrust();
        appEntrust.setNid(SecurityUtils.getUserId());
        appEntrust.setClientId(clientId);

        appEntrustMapper.insert(appEntrust);
        cacheClient.delete(KEY + code);

        return 1;
    }

    /**
     * 修改委托关系
     *
     * @param appEntrust 委托关系
     * @return 结果
     */
    @Override
    public int updateAppEntrust(AppEntrust appEntrust) {
        return appEntrustMapper.updateById(appEntrust);
    }


    /**
     * 删除委托关系信息
     *
     * @param id 委托关系主键
     * @return 结果
     */
    @Override
    public int deleteAppEntrustById(Long id) {
        AppEntrust appEntrust = new AppEntrust();
        appEntrust.setId(id);
        appEntrust.setDelFlag(DBDataStatus.DELETED.getCode());
        return appEntrustMapper.updateById(appEntrust);
    }

    @Override
    public List<MemberAvatar> turn(Integer pageSize, Long lastId, String search) {
        LambdaQueryWrapper<AppEntrust> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(AppEntrust::getCreateTime);
        wrapper.eq(AppEntrust::getDelFlag, DBDataStatus.OK.getCode());
        wrapper.eq(AppEntrust::getNid, SecurityUtils.getUserId());

        if (lastId != null) {
            wrapper.lt(AppEntrust::getId, lastId);
        }

        PageHelper.startPage(1, pageSize);
        List<AppEntrust> appEntrusts = this.appEntrustMapper.selectList(wrapper);
        if (appEntrusts.isEmpty()) {
            return new ArrayList<>();
        }
        List<Long> ids = appEntrusts.stream().map(AppEntrust::getClientId).collect(Collectors.toList());

        return appMemberInfoService.queryMemberAvatar(ids);

    }

    @Autowired
    private CacheClient cacheClient;

    private static String KEY = "APP_ENTRUST_KEY:";

    @Override
    public String code() {
        boolean isOk = false;
        StringBuilder key = new StringBuilder();
        synchronized (this) {
            for (int i = 0; i < 10; i++) {
                int randomNum = new Random().nextInt(90000) + 10000;
                char c = (char) (new Random().nextInt(26) + 65);
                char c2 = (char) (new Random().nextInt(26) + 65);
                key.append(c).append(c2).append(randomNum);
                Object cacheObject = cacheClient.getCacheObject(KEY + key);
                if (cacheObject == null) {
                    isOk = true;
                    cacheClient.setCacheObject(KEY + key, SecurityUtils.getUserId(), 60 , TimeUnit.SECONDS);
                    break;
                }
            }
        }

        if (!isOk) {
            return null;
        }
        return key.toString();
    }

    public static void main(String[] args) {
        System.out.println(System.currentTimeMillis());
    }
}
